package com.brite.android.game.menu;

import java.util.ArrayList;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.FrameLayout;

import com.brite.android.game.R;
import com.brite.android.game.achievement.HighScoreActivity;
import com.brite.android.game.action.Cordinate;
import com.brite.android.game.action.LoadStoryActivity;
import com.brite.android.game.action.Region;
import com.brite.android.game.action.TimeCounter;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class MainMenu extends BaseGameActivity {

	private int CAMERA_WIDTH = 480;
	private int CAMERA_HEIGHT = 320;
	
	private Scene scene;
	
	private Texture bgTexture;
	private TextureRegion bgTextureRegion;
	
	private Texture[] menuItemTextures;
	private TiledTextureRegion[] menuItemTiledTextureRegions;
	private String[] menuItemSourceImgPath = {"btnStart.png", "btnHighScore.png", "btnSetting.png", "btnExit.png"};
	@SuppressWarnings("rawtypes")
	private Class[] classToActiveActivity = {LoadStoryActivity.class, HighScoreActivity.class, SettingActivity.class, null};
	private boolean[] classActive = {false, false, false, false};
	private float[] rotate_ = {-30, -15, 0, 15};
//	private float[] rotate_ = {-30, -15};
	
	float totalHeightMenuItem = 0;
	
	private TimeCounter timeToActiveMenuItem = new TimeCounter(1f);
	
	private ArrayList<AnimatedSprite> arrListMenuItemAnimatedSprites = new ArrayList<AnimatedSprite>();
	
	
	@Override
	public Engine onLoadEngine() {
		// TODO Auto-generated method stub
		Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		EngineOptions eo = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
		eo.setNeedsMusic(true);
		eo.setNeedsSound(true);
		mEngine = new Engine(eo);
		
		return mEngine;
	}

	@Override
	public void onLoadResources() {
		TextureRegionFactory.setAssetBasePath("gfx/");
		
		bgTexture = new Texture(1024, 1024, TextureOptions.DEFAULT);
		bgTextureRegion = TextureRegionFactory.createFromAsset(bgTexture, this, "menu_game.png", 0, 0);
		
		menuItemTextures = new Texture[menuItemSourceImgPath.length];
		menuItemTiledTextureRegions = new TiledTextureRegion[menuItemSourceImgPath.length];
		
		for (int i = 0; i < menuItemTextures.length; i++) {
			menuItemTextures[i] = new Texture(512, 64, TextureOptions.DEFAULT);
			menuItemTiledTextureRegions[i] = TextureRegionFactory.createTiledFromAsset(menuItemTextures[i], this, menuItemSourceImgPath[i], 0, 0, 2, 1);
			mEngine.getTextureManager().loadTexture(menuItemTextures[i]);
		}
		
		mEngine.getTextureManager().loadTextures(bgTexture);
	}

	@Override
	public Scene onLoadScene() {
		scene = new Scene(1);
		
		Sprite bgSprite = new Sprite(0, 0, bgTextureRegion);
		bgSprite.setWidth(CAMERA_WIDTH);
		bgSprite.setHeight(CAMERA_HEIGHT);
		scene.attachChild(bgSprite);
		
		for (int i = 0; i < menuItemTiledTextureRegions.length; i++) {
			totalHeightMenuItem += menuItemTiledTextureRegions[i].getTileHeight();
		}
		
		float distanceBetweenMenuItem = (CAMERA_HEIGHT/2 - totalHeightMenuItem) / (menuItemTiledTextureRegions.length + 2);
		
		for (int i = 0; i < menuItemTiledTextureRegions.length; i++) {
			AnimatedSprite menuItem = new AnimatedSprite(0, 0, menuItemTiledTextureRegions[i]);
			arrListMenuItemAnimatedSprites.add(menuItem);
			scene.attachChild(menuItem);
		}

		for (int i = 0; i < arrListMenuItemAnimatedSprites.size(); i++) {
			AnimatedSprite menuItem = arrListMenuItemAnimatedSprites.get(i);
			
			if (i==0) {
				menuItem.setPosition(0, CAMERA_HEIGHT/2 + distanceBetweenMenuItem);
			}else {
				menuItem.setPosition(0, arrListMenuItemAnimatedSprites.get(i-1).getY() + arrListMenuItemAnimatedSprites.get(i-1).getHeightScaled() + distanceBetweenMenuItem);
			}
		}
		
		scene.registerUpdateHandler(new IUpdateHandler() {
			
			@Override
			public void reset() {
				
			}
			
			@Override
			public void onUpdate(float pSecondsElapsed) {
				for (int i = 0; i < classActive.length; i++) {
					if (classActive[i]) {
						timeToActiveMenuItem.update(pSecondsElapsed);
						break;
					}
				}
				if (!timeToActiveMenuItem.currentStatus()) {
					changeActivity();
				}
			}
		});
		
		scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
			
			@Override
			public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
				for (int i = 0; i < arrListMenuItemAnimatedSprites.size(); i++) {
					AnimatedSprite menuItem = arrListMenuItemAnimatedSprites.get(i);
					Region menuItemRegion = new Region(menuItem.getX(), menuItem.getY(), menuItem.getWidthScaled(), menuItem.getHeightScaled());
					if (menuItemRegion.isCovered(new Cordinate(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()), menuItemRegion)) {
						for (int j = 0; j < arrListMenuItemAnimatedSprites.size(); j++) {
							animationOfMenuItem(arrListMenuItemAnimatedSprites.get(j), rotate_[j]);
						}
						classActive[i] = true;
						timeToActiveMenuItem.start();
//						startActivity(new Intent(getBaseContext(), classToActiveActivity[i]));
//						finish();
						break;
					}
				}
				
				return false;
			}
		});
		
		return scene;
	}

	private void changeActivity(){
		for (int i = 0; i < classActive.length; i++) {
			if (classActive[i]) {
				if (i != classActive.length-1) {
					startActivity(new Intent(getBaseContext(), classToActiveActivity[i]));
					classActive[i] = false;
					finish();
				}else if (i == classActive.length-1) {
					classActive[i] = false;
					exitGame();
				}
					
				break;
			}
		}

	}
	
	private void animationOfMenuItem(AnimatedSprite menuItemAnimatedSprite, float rotate){
		menuItemAnimatedSprite.setCurrentTileIndex(menuItemAnimatedSprite.getCurrentTileIndex() == 0 ? 1 : 0);
		
		float distanceBetweenMenuItem = (CAMERA_HEIGHT - totalHeightMenuItem) / (menuItemTiledTextureRegions.length + 2);
		
		for (int i = 0; i < arrListMenuItemAnimatedSprites.size(); i++) {
			AnimatedSprite menuItem = arrListMenuItemAnimatedSprites.get(i);
			
			if (i==0) {
				menuItem.setPosition(0, distanceBetweenMenuItem);
			}else {
				menuItem.setPosition(0, arrListMenuItemAnimatedSprites.get(i-1).getY() + arrListMenuItemAnimatedSprites.get(i-1).getHeightScaled() + distanceBetweenMenuItem);
			}
		}
		
		menuItemAnimatedSprite.setRotation(rotate);
	}
	
	@Override
	public void onLoadComplete() {
		// TODO Auto-generated method stub

	}

	@Override
    protected void onSetContentView() {
        final FrameLayout frameLayout = new FrameLayout(this);
        final FrameLayout.LayoutParams frameLayoutLayoutParams =
                new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
                                             FrameLayout.LayoutParams.FILL_PARENT);
 
        final AdView adView = new AdView(this, AdSize.IAB_BANNER, "a14fbdf32995e3c");
        adView.refreshDrawableState();
        adView.setVisibility(AdView.VISIBLE);
        final FrameLayout.LayoutParams adViewLayoutParams =
                new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
                                             FrameLayout.LayoutParams.WRAP_CONTENT,
                                             Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
        // getHeight returns 0
        // http://groups.google.com/group/admob-pu ... a874df3472
        int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50,
                getResources ().getDisplayMetrics ());
        // top of AD is at middle of the screen
//        adViewLayoutParams.topMargin = height/2;
//        adViewLayoutParams.topMargin = 0;
        Log.v("Add H", "Adview height : " + height);
        Log.v("Add S", "Adview size {x:" + adView.getWidth() + ", y: " + adView.getHeight()+ "}");
 
        AdRequest adRequest = new AdRequest();
        adRequest.setTesting(true);
        adView.loadAd(adRequest);
        if (adView.isReady()) {
        	Log.v("Add S", "Adview size {x:" + adView.getWidth() + ", y: " + adView.getHeight()+ "}");
		}
        adView.setPadding(0, 0, 0, CAMERA_HEIGHT - adView.getHeight() - 60);
        
        this.mRenderSurfaceView = new RenderSurfaceView(this);
        mRenderSurfaceView.setRenderer(mEngine);
 
        final android.widget.FrameLayout.LayoutParams surfaceViewLayoutParams =
                new FrameLayout.LayoutParams(super.createSurfaceViewLayoutParams());
 
        frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
        frameLayout.addView(adView, adViewLayoutParams);
 
        this.setContentView(frameLayout, frameLayoutLayoutParams);
    }
	
	final protected Dialog onCreateDialog(int id) { 
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setIcon(R.drawable.icon_game)
		.setTitle("EXIT")
		.setMessage("Are you sure you want to exit?")
		.setCancelable(false)
		.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				finish();
			}
		})
		.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});

		Dialog dialog = builder.create();
		dialog.setCancelable(false); 
		return dialog;
	}

	private void exitGame(){
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				MainMenu.this.showDialog(0);
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitGame();
		}
		return super.onKeyDown(keyCode, event);
	}
}
